package handler

import (
	"github.com/gin-gonic/gin"
	"tie/api/register"
	"tie/initlist/mysql"
	"tie/inits/model"
)

func Like(r *gin.Context) {
	var req register.Like
	err := r.ShouldBind(&req)
	if err != nil {
		r.JSON(400, &Res{
			Code:    400,
			Message: "参数失败",
			Data:    nil,
		})
		return
	}
	tr := mysql.DB.Begin()
	like := model.Like{
		UserId:    req.UserId,
		TieId:     req.TieId,
		LikeCount: req.LikeCount,
	}
	if like.LikeCount != 1 {
		tr.Rollback()
		r.JSON(400, &Res{
			Code:    400,
			Message: "一个用户只能点赞一次",
			Data:    nil,
		})
		return
	}
	tr.Commit()
	mysql.DB.Debug().Create(&like)
	r.JSON(200, &Res{
		Code:    200,
		Message: "点赞成功",
		Data:    like,
	})
}

func LikeDel(r *gin.Context) {
	var req register.Like
	err := r.ShouldBind(&req)
	if err != nil {
		r.JSON(400, &Res{
			Code:    400,
			Message: "参数失败",
			Data:    nil,
		})
		return
	}

	var like model.Like
	err = mysql.DB.Debug().Where("id = ?", like.ID).Delete(&model.Like{}).Error
	if err != nil {
		r.JSON(400, &Res{
			Code:    400,
			Message: "删除失败",
			Data:    nil,
		})
		return
	}
	r.JSON(200, &Res{
		Code:    200,
		Message: "取消点赞成功",
		Data:    like.ID,
	})
}
